<template>
<div>
  <a-modal
    title="发送消息"
    :keyboard="false"
    :maskClosable="false"
    :closable="false"
    v-model="show"
    @cancel="cancel"
    :confirmLoading="loading"
    @ok="sendMessages">
    <a-form :form="form">
      <a-form-item label='目标用户' v-bind="formItemLayout">
        <a-select
          mode="multiple"
          :allowClear="true"
          v-decorator="['userNames']"
          >
          <a-select-option v-for="r in userData" :key="r.username">{{r.username}}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label='消息内容' v-bind="formItemLayout">
        <a-textarea
          :auto-size="{ minRows: 3, maxRows: 20 }"
          v-decorator="['message']"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</div>
</template>
<script>
const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 18 }
}

export default {
  beforeCreate () {
    this.form = this.$form.createForm(this)
  },
  props: {
    userMessageAddVisible: {
      default: false
    }
  },
  data () {
    return {
      formItemLayout,
      userData: [],
      loading: false
    }
  },
  computed: {
    show: {
      get: function () {
        return this.userMessageAddVisible
      },
      set: function () {
      }
    }
  },
  methods: {
    cancel () {
      this.form.resetFields()
      this.$emit('cancel')
    },
    sendMessages () {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.loading = true
          this.$put('admin/userMessage', {
            userNames: this.form.getFieldValue('userNames'),
            message: this.form.getFieldValue('message')
          }).then((res) => {
            if (res.data.status) {
              this.$emit('success')
              this.form.resetFields()
              this.loading = false
            } else {
              this.loading = false
              this.$message.error(res.data.message)
            }
          })
        }
      })
    }
  },
  watch: {
    userMessageAddVisible () {
      if (this.userMessageAddVisible) {
        this.loading = false
        this.$get('user').then((r) => {
          this.userData = r.data.rows
        })
      }
    }
  }
}
</script>
